<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <Sidebar 
      :map-list="mapList"
      :current-map="currentMap"
      :show-jurisdiction="sidebarState.showJurisdiction"
      :show-labels="sidebarState.showLabels"
      :is-3d="sidebarState.is3D"
      :rotation="sidebarState.rotation"
      :pitch="sidebarState.pitch"
      :use-merged-data="useMergedData"
      :data-version="dataVersion"
      :building-count="buildingCount"
      @select-map="handleSelectMap"
      @reload="handleSidebarReload"
      @fit-view="handleSidebarFitView"
      @toggle-3d="handleSidebarToggle3D"
      @toggle-jurisdiction="handleSidebarToggleJurisdiction"
      @toggle-labels="handleSidebarToggleLabels"
      @download="handleSidebarDownload"
      @data-version-change="handleDataVersionChange"
      @rotation-change="handleSidebarRotationChange"
      @pitch-change="handleSidebarPitchChange"
    />
    
    <!-- 地图区域 -->
    <div class="map-wrapper">
      <MapView 
        ref="mapViewRef"
        :map-data="currentMap"
        @map-loaded="handleMapLoaded"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import Sidebar from './components/Sidebar.vue'
import MapView from './components/MapView.vue'

// 状态
const mapList = ref([])
const currentMap = ref(null)
const mapViewRef = ref(null)
const dataVersion = ref('merged') // 'merged' 或 'full'
const useMergedData = ref(true) // 默认使用精简版

// 侧边栏状态（从 MapView 同步）
const sidebarState = ref({
  showJurisdiction: true,
  showLabels: true,
  is3D: true,
  rotation: 0,
  pitch: 50
})

// 计算楼宇总数
const buildingCount = computed(() => {
  let count = 0
  mapList.value.forEach(map => {
    if (map.数据?.工作站点位) {
      map.数据.工作站点位.forEach(station => {
        count += station.覆盖楼宇数量 || 0
      })
    }
  })
  return count
})

// 加载地图数据
const loadMapData = async (version = 'merged') => {
  try {
    // 根据版本选择不同的数据文件
    const dataFile = version === 'merged' ? '/map_data_merged.json' : '/map_data_full.json'
    
    console.log(`📂 加载${version === 'merged' ? '精简版' : '完整版'}数据: ${dataFile}`)
    
    // 添加时间戳参数禁用缓存
    const timestamp = new Date().getTime()
    const response = await fetch(`${dataFile}?t=${timestamp}`)
    if (!response.ok) {
      throw new Error(`无法加载数据文件: ${dataFile}`)
    }
    const data = await response.json()
    mapList.value = Object.entries(data.地图数据).map(([key, value]) => ({
      key,
      ...value
    }))
    
    // 如果之前有选中的地图，尝试保持选中状态
    if (currentMap.value) {
      const previousKey = currentMap.value.key
      const stillExists = mapList.value.find(m => m.key === previousKey)
      if (stillExists) {
        currentMap.value = stillExists
      } else {
        currentMap.value = null
      }
    }
    
    dataVersion.value = version
    
    const versionText = version === 'merged' ? '精简版' : '完整版'
    ElMessage.success({
      message: `${versionText}数据加载成功！共 ${mapList.value.length} 张地图`,
      duration: 2000
    })
  } catch (error) {
    console.error('加载地图数据失败:', error)
    ElMessage.error('加载地图数据失败: ' + error.message)
  }
}

// 处理数据版本切换
const handleDataVersionChange = (useMerged) => {
  const newVersion = useMerged ? 'merged' : 'full'
  console.log(`🔄 切换数据版本: ${dataVersion.value} → ${newVersion}`)
  
  // 保存用户选择到 localStorage
  localStorage.setItem('mapDataVersion', newVersion)
  
  // 重新加载数据
  loadMapData(newVersion)
}

// 选择地图
const handleSelectMap = (mapKey) => {
  const selected = mapList.value.find(m => m.key === mapKey)
  if (selected) {
    currentMap.value = selected
  }
}

// 地图加载完成
const handleMapLoaded = () => {
  console.log('地图加载完成')
  // 同步状态
  nextTick(() => {
    if (mapViewRef.value) {
      sidebarState.value.showJurisdiction = mapViewRef.value.getShowJurisdiction()
      sidebarState.value.showLabels = mapViewRef.value.getShowLabels()
      sidebarState.value.is3D = mapViewRef.value.getIs3D()
      sidebarState.value.rotation = mapViewRef.value.getRotation()
      sidebarState.value.pitch = mapViewRef.value.getPitch()
    }
  })
}

// 处理侧边栏事件
const handleSidebarReload = () => {
  if (mapViewRef.value) {
    mapViewRef.value.reloadMap()
  }
}

const handleSidebarFitView = () => {
  if (mapViewRef.value) {
    mapViewRef.value.fitView()
  }
}

const handleSidebarToggle3D = () => {
  if (mapViewRef.value) {
    mapViewRef.value.toggle3D()
    // 同步状态
    nextTick(() => {
      sidebarState.value.is3D = mapViewRef.value.getIs3D()
    })
  }
}

const handleSidebarToggleJurisdiction = () => {
  if (mapViewRef.value) {
    mapViewRef.value.toggleJurisdiction()
    // 同步状态
    nextTick(() => {
      sidebarState.value.showJurisdiction = mapViewRef.value.getShowJurisdiction()
    })
  }
}

const handleSidebarToggleLabels = () => {
  if (mapViewRef.value) {
    mapViewRef.value.toggleLabels()
    // 同步状态
    nextTick(() => {
      sidebarState.value.showLabels = mapViewRef.value.getShowLabels()
    })
  }
}

const handleSidebarDownload = () => {
  if (mapViewRef.value) {
    mapViewRef.value.handleDownload()
  }
}

const handleSidebarRotationChange = (angle) => {
  if (mapViewRef.value) {
    mapViewRef.value.setRotation(angle)
    // 同步状态
    nextTick(() => {
      sidebarState.value.rotation = mapViewRef.value.getRotation()
    })
  }
}

const handleSidebarPitchChange = (angle) => {
  if (mapViewRef.value) {
    mapViewRef.value.setPitch(angle)
    // 同步状态
    nextTick(() => {
      sidebarState.value.pitch = mapViewRef.value.getPitch()
      sidebarState.value.is3D = mapViewRef.value.getIs3D()
    })
  }
}

// 生命周期
onMounted(() => {
  // 从 localStorage 读取用户上次的选择
  const savedVersion = localStorage.getItem('mapDataVersion') || 'merged'
  useMergedData.value = savedVersion === 'merged'
  dataVersion.value = savedVersion
  
  console.log(`💾 恢复用户选择: ${savedVersion === 'merged' ? '精简版' : '完整版'}`)
  
  loadMapData(savedVersion)
})
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
  position: relative;
}

.map-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
}
</style>

